//
//  GoodsDetailViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/10.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "GoodsDetailViewController.h"
#import "GoodsDetailModel.h"
#import "GoodsSelectViewController.h"
#import "SureOderViewController.h"
#import "MallRequestManager.h"
#import "GoodsDetailCell.h"
#import "ScorePayViewController.h"
#import "AddressViewController.h"
#import "LoginViewController.h"
#import "ImageViewController.h"
@interface GoodsDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate,UIAlertViewDelegate>
{
    NSArray *_goodselectDataArray;
    UIScrollView *_imgScroll;
    UIPageControl *_pageControl;
}
@property (nonatomic,strong)UITableView *tableView;
@property(strong,nonatomic)UIWindow *window;
@property(strong,nonatomic)UIButton *button;
@property(nonatomic,strong)GoodsSelectViewController *GoodsSelectVC;
@property (nonatomic,strong)ScorePayViewController *scorePayVC;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)UIButton *btnView;
@property (nonatomic,assign)int flag;
@end
@implementation GoodsDetailViewController
-(void)viewWillAppear:(BOOL)animated
{
    self.tableView.scrollEnabled = YES;
}
- (void)createUI
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.backgroundColor  = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.allowsSelection =NO;
    self.tableView.tableFooterView.backgroundColor = [UIColor whiteColor];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 200)];
    view.backgroundColor = [UIColor whiteColor];
    _imgScroll = [[UIScrollView alloc]initWithFrame:view.frame];
    float imageW = _imgScroll.frame.size.width;
    float imageH = _imgScroll.frame.size.height;
    _imgScroll.backgroundColor= [UIColor whiteColor];
    [self.tableView addSubview:_imgScroll];
    //隐藏水平滚动条
    _imgScroll.showsHorizontalScrollIndicator = NO;
    _imgScroll.showsVerticalScrollIndicator = NO;
    _imgScroll.pagingEnabled =YES;
    _imgScroll.delegate = self;
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(self.tableView.frame.size.width/2-50, 180, 100, 20)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 180, self.tableView.frame.size.width, 20)];
    [self.tableView addSubview:bgView];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.alpha = 0.4;
    [self.tableView addSubview:_pageControl];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    //设置page总页数
   
    GoodsDetailModel *model = [self.dataSource objectAtIndex:0];
    NSString *show_images = model.showImage;
    NSArray *imgArr = [show_images componentsSeparatedByString:@","];
    _pageControl.numberOfPages = imgArr.count;
    _pageControl.currentPage = 0;
    if (imgArr.count <2) {
        _pageControl.hidden =YES;
    }
        for (int i = 0; i<imgArr.count; i++) {
            _imgScroll.contentSize = CGSizeMake(imageW*(i+1), imageH);
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(imageW*i, 0, imageW, imageH)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:imgArr[i]] placeholderImage:[UIImage imageNamed:@"商城首页默认图片"]];
//            [imageView setContentMode:UIViewContentModeScaleXAspectFit];
            [_imgScroll addSubview:imageView];
        }
    self.tableView.tableHeaderView = view;
    [self performSelector:@selector(createButton) withObject:nil afterDelay:0];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodsDetailCell" bundle:nil] forCellReuseIdentifier:@"GoodsDetailCell"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商品详情";
     [self requestData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushToGoodsSelectVC:) name:sureIsClicked object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PushToScorePayVC:) name:PushToScorePayVC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushToAddressVC) name:pushToAddressVC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(noAddressOfScore) name:noAddressOfScore object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(noAddressOfSureOderView) name:noAddressOfSureOderView object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeGoodSelectVC) name:removeGoodSelectVC object:nil];
    [self showNavgationWithLeftItemWithTitle:@"返回"];
}
- (void)removeGoodSelectVC
{
    
    [_GoodsSelectVC.view removeFromSuperview];
}
- (void)noAddressOfSureOderView
{
    [self.GoodsSelectVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
    self.tableView.allowsSelection = YES;
}
- (void)noAddressOfScore
{
    [self.scorePayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
    self.tableView.allowsSelection = YES;
}
- (void)pushToAddressVC
{
    AddressViewController *address = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"address"];
    address.flag = 0;
    [self.navigationController pushViewController:address animated:YES];

}
- (void)pushToGoodsSelectVC:(NSNotification *)text
{
    SureOderViewController *sureOder = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"sureOder"];
    sureOder.goodInfo = text.userInfo;
    [self.navigationController pushViewController:sureOder animated:NO];
}

- (void)PushToScorePayVC:(NSNotification *)text
{
    NSLog(@"text:%@",text.userInfo);
    [self.GoodsSelectVC.view removeFromSuperview];
    self.scorePayVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"ScorePay"];
    [self addChildViewController:self.scorePayVC];
    [self.view addSubview:self.scorePayVC.view];
    self.scorePayVC.dataDic = text.userInfo;
    self.scorePayVC.view.frame = CGRectMake(0, self.tableView.frame.size.height-270, self.view.frame.size.width, 270);
    self.scorePayVC.view.alpha = 1.0;
    int score = [[[text.userInfo objectForKey:@"goodsInfo"] objectForKey:@"price"]intValue];
    self.scorePayVC.scoreLabel.text = [NSString stringWithFormat:@"%d",[[text.userInfo objectForKey:@"number"]intValue]*score];
}
- (void)requestData
{
    [self.dataSource removeAllObjects];
    NSString *userID;
    NSString *token;
    if (self.youke ==YES) {
        userID = @"0";
        token = Tmptoken;
    }else
    {
        userID = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    }
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userID forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    [params setValue:self.goodsId forKey:@"good_id"];
     [SVProgressHUD showWithStatus:@"获取商品详情信息.." maskType:SVProgressHUDMaskTypeClear];
    [MallRequestManager post:Querygoodsinfo RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                TIPSFORVIEW(@"获取商品信息失败");
            });
        }else{
            NSString *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            NSDictionary *dic =   [self changeType:responseObject];
            if ([dic.allKeys containsObject:@"result"]) {
                NSDictionary *result = [dic objectForKey:@"result"];
                self.dataSource = [NSMutableArray new];
                if (result.count>0) {
                    [self.dataSource addObject:[GoodsDetailModel appWithDict:result]];
                }
                [self performSelectorOnMainThread:@selector(createUI) withObject:nil waitUntilDone:NO];
            }
        }
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    GoodsDetailModel *model = [self.dataSource objectAtIndex:0];
    NSArray *array = [model.introduceImages componentsSeparatedByString:@","];
    return array.count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 200;
    }else
    {
        GoodsDetailModel *model = [self.dataSource objectAtIndex:0];
        NSString *introduce_images = model.introduceImages;
        NSArray *introArr = [introduce_images componentsSeparatedByString:@","];
       
            NSString *str1 = [NSString stringWithFormat:@"%@",introArr[indexPath.row-1]];
            NSArray *tmpArr1 = [str1 componentsSeparatedByString:@"_size_"];
            NSString *str2 =  [tmpArr1 objectAtIndex:1];
            NSArray *tmpArr2 = [str2 componentsSeparatedByString:@"."];
            NSString *str3 = [tmpArr2 objectAtIndex:0];
            NSArray *imgArr = [str3 componentsSeparatedByString:@"*"];
            float imageW = self.tableView.frame.size.width-16;
            float w = [[imgArr objectAtIndex:0]floatValue];
            float h = [[imgArr objectAtIndex:1]floatValue];
            float rate = w/imageW;
            float imageH = h/rate;
            return imageH;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString *CellID = @"GoodsDetailCell";
        GoodsDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
        GoodsDetailModel *model = self.dataSource[indexPath.row];
        _goodselectDataArray  = model.standard;
        cell.model = model;
        
        return cell;
    }else
    {
        static NSString *cellID = @"ImageCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
//        if (cell ==nil) {
             cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
//        }
        GoodsDetailModel *model = self.dataSource[0];
        NSArray *introArr = [model.introduceImages componentsSeparatedByString:@","];
        NSURL *url = [NSURL URLWithString:[introArr objectAtIndex:indexPath.row-1]];
       CGFloat height =  [self tableView:self.tableView heightForRowAtIndexPath:indexPath];
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(8, 0, self.tableView.frame.size.width-16, height)];
        //为UIImageView1添加点击事件
        UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanBigImageClick:)];
        [imgview addGestureRecognizer:tapGestureRecognizer1];
        imgview.tag = (indexPath.row-1)+100;
        //让UIImageView和它的父类开启用户交互属性
        [imgview setUserInteractionEnabled:YES];
        [cell addSubview:imgview];
        [imgview sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"商城首页默认图片"]];
        return cell;
    }
}
//点击查看大图
-(void)scanBigImageClick:(UITapGestureRecognizer *)tap{
    NSLog(@"点击图片");
    ImageViewController *imageVC = [[ImageViewController alloc]init];
    UIImageView *clickedImageView = (UIImageView *)tap.view;
    NSInteger imgIndex =  clickedImageView.tag;
    GoodsDetailModel *model = [self.dataSource objectAtIndex:0];
    NSString *introduce_images = model.introduceImages;
    NSArray *introArr = [introduce_images componentsSeparatedByString:@","];
    imageVC.imgArray = introArr;
    imageVC.imgIndex = imgIndex-100;
    [self presentViewController:imageVC animated:NO completion:nil];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 70;
}
- (void)createButton
{
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setTitle:@"立即购买" forState:UIControlStateNormal];
    [_button setFont:[UIFont systemFontOfSize:20]];
    _button.layer.cornerRadius = 25;
    _button.frame = CGRectMake(8,10, self.view.frame.size.width-16, 50);
    [_button setBackgroundColor:[UIColor orangeColor]];
    [_button addTarget:self action:@selector(resignWindow) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-70, self.view.frame.size.width, 70)];
    view.backgroundColor = [UIColor whiteColor];
    [view addSubview:_button];
    [self.view addSubview:view];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==1) {
        LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
        BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:login];
        [UIApplication sharedApplication].delegate.window.rootViewController = baseNav;
    }else
    {
        return;
    }
}
- (void)resignWindow
{
    //添加蒙层
    if ( self.youke ==YES) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登录,是否立即登录" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alter.delegate = self;
        [alter show];
        return;
    }
    self.btnView = [[UIButton alloc]initWithFrame:self.tableView.bounds];
    self.btnView.backgroundColor = [UIColor grayColor];
    [self.btnView addTarget:self action:@selector(btnViewClicked) forControlEvents:UIControlEventTouchUpInside];
    self.btnView.alpha = 0.6;
    [self.tableView addSubview:self.btnView];
    self.GoodsSelectVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"GoodsSelectVC"];
    [self addChildViewController:self.GoodsSelectVC];
     [self.view addSubview:self.GoodsSelectVC.view];
    self.GoodsSelectVC.view.frame = CGRectMake(0, self.tableView.frame.size.height-400, self.view.frame.size.width, 400);
    self.GoodsSelectVC.view.alpha = 1.0;
    //将需要的数据向后面页面传递
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setObject:_goodselectDataArray forKey:@"userInfo"];
    GoodsDetailModel *model = self.dataSource[0];
    NSString *price = model.discountprice;
    [dict setObject:price forKey:@"price"];
    NSString *goodsTitle = model.goodTitle;
    [dict setObject:goodsTitle forKey:@"goodsTitle"];
    NSString *score = model.score;
    [dict setObject:score forKey:@"score"];
    NSString *type = model.type;
    [dict setObject:type forKey:@"type"];
    //通知给商品选择页面传值 商品信息
    NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    self.tableView.scrollEnabled =NO;
}
- (void)btnViewClicked
{
    self.tableView.scrollEnabled =YES;
    [_GoodsSelectVC.view removeFromSuperview];
    [_scorePayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
     [self performSelector:@selector(createButton) withObject:nil afterDelay:0];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView ==_imgScroll) {
        CGFloat scroll = scrollView.frame.size.width;
        int p = (scrollView.contentOffset.x+scroll*0.5)/scroll;
        
        _pageControl.currentPage = p;
    }
}
#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
-(id)changeType:(id)myObj{
    if ([myObj isKindOfClass:[NSDictionary class]]){
        return [self nullDic:myObj];
    }else if([myObj isKindOfClass:[NSArray class]]){
        return [self nullArr:myObj];
    }else if([myObj isKindOfClass:[NSString class]]){
        return [self stringToString:myObj];
    }else if([myObj isKindOfClass:[NSNull class]]){
        return [self nullToString];
    }else{
        return myObj;
    }
}
//将Null类型的项目转化成@""
-(NSString *)nullToString{
    return @"";
}

//将NSDictionary中的Null类型的项目转化成@""
-(NSArray *)nullArr:(NSArray *)myArr{
    NSMutableArray *resArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < myArr.count; i ++){
        id obj = myArr[i];
        obj = [self changeType:obj];
        [resArr addObject:obj];
    }
    return resArr;
}
//将NSString类型的判空后返回
- (NSString *)stringToString:(NSString *)string{
    if([string isEqualToString:@"(null)"] || [string isEqualToString:@"<nil>"] || string == nil || string == NULL){
        return @"";
    }
    return string;
}

- (NSDictionary *)nullDic:(NSDictionary *)myDic{
    NSArray *keyArr = [myDic allKeys];
    NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
    for (int i = 0; i < keyArr.count; i ++){
        id obj = [myDic objectForKey:keyArr[i]];
        obj = [self changeType:obj];
        [resDic setObject:obj forKey:keyArr[i]];
    }
    return resDic;
}
@end
